<?php
include_once 'admin.php';
class adminErpController extends adminController {

    public function __construct() {
        parent::__construct();
        $this->erpManageDb =  $this->in_db('erpManageDb');
    }
    /**
     * 库存管理列表
     */
    public function dogetErpProductList() {
        $code   = common::request('code','R','');//货号
        $name   = common::request('name','R','');//名称
        $status = common::request('status','R',0);//状态
        $categoryId = common::request('categoryId','R',0);//状态
        $listNum = 20;
        $p = common::request('p', 'G', 1);
        $start = ($p - 1) * $listNum;
        $parameter = '';
        $params = [];
        if (trim($code)) {
            $parameter .= '&code='."$code";
            $params['code'] = $code;
        }
        if (trim($name)) {
            $parameter .= '&title='."$name";
            $params['name'] = $name;
        }
        if ($status) {
            $parameter .= '&status='."$status";
            $params['status'] = $status;
        }

        if ($categoryId) {
            $parameter .= '&categoryId='."$categoryId";
            $params['cid'] = $categoryId;
        }
        $params['start'] = $start;
        $params['limit'] = $listNum;
        $info = $this->load('adminErp')->getProductList($params);
        $total = $this->load('adminErp')->total;
        require FILE . 'lib/page.class.php';
        $page = new Page($total, $listNum, $parameter);
        $pageStr = $page->show();

        $arrCategoryList = $this->load('adminErp')->getCategoryListForSelect(); //查询分类
        if ($info) {
           foreach($info as $key=>$val) {
               foreach ($arrCategoryList as $k=>$v) {//优化
                   if ($val['category_id'] == $v['id']) {
                       $info[$key]['categoryName'] = $v['title'];
                       break;
                   }
               }
           }
        }
        $this->view->assign('arrCategoryList', $arrCategoryList);
        $this->view->assign('info', $info);
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('name', $name);
        $this->view->assign('code', $code);
        $this->view->assign('status', $status);
        $this->view->assign('categoryId', $categoryId);
        $this->view->display('erp/productList');
    }

    /**
     * 补货
     */
    public function dogetProductStandard() {
        $pid = common::request('pid','R','');//货品ID
        if (!$pid) {
            common::tips('货品参数丢失');
            exit;
        }
        $this->view->assign('pid',$pid);
        //查询货品的规格
        $info = $this->load('adminErp')->getProductStandard($pid);
        //var_dump($info);
        $this->view->assign('info',$info);
        $list = $this->load('adminErp')->getGoodsListByProductMixed($pid,1);//查询货品的规格商品
        $this->view->assign('list',$list);
        $this->view->display('erp/addGoodsNum');

    }

    /**
     * ajax补货操作
     */
    public function doreplenishGoods() {
        $pid = common::request('pid','P',0);//货品ID
        $gid = common::request('gid','P',0);//商品ID
        $stockIntoCnt = common::request('stockIntoCnt','P',0);//入库数量
        $price = common::request('price','P',0);//单价
        if (!$pid || !$gid || !$stockIntoCnt || !$price) {
            echo json_encode(array('status'=>'fail','error_msg'=>'参数丢失')); exit;
        }
        /*检测数据start*/
        $fields = [];
            foreach($gid as $key=>$val) {
                if (!is_numeric($val) || !(int)$val) {
                    echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行规格参数丢失')); exit;
                }
                if (!preg_match('/^[1-9]+[0-9]*$/',$stockIntoCnt[$key],$match)) {
                    echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行入库数量是正整数且必须>0')); exit;
                }
                if (!preg_match('/^[1-9][0-9]*(\.[0-9]{1,2})?$/', $price[$key],$match) && !preg_match('/^[0-9]\.0[1-9]$/', $price[$key],$match2) && !preg_match('/^[0-9]\.[1-9][0-9]?$/', $price[$key],$match3)) {
                    echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行单价必须>0,最多2位小数')); exit;
                }
                $fields[] = array('gid'=>(int)$val,'stockIntoCnt'=>(int)$stockIntoCnt[$key],'price'=>(float)round($price[$key],2),'product_id'=>$pid);
            }
        /*检测数据end*/
        $okCnt =0;
        foreach ($fields as $key=>$val) {
            $r = $this->load('adminErp')->setGoodsStockNum($val['product_id'],$val['gid'],$val['stockIntoCnt'],$val['price']);
            if ($r){
                $this->load('adminErp')->addErpLog(2,$val['product_id'],2,' 货品ID为'.$pid.'规格商品ID为'.$val['gid'].'补货'.$val['stockIntoCnt'].'件，单价：'.$val['price']);
                $okCnt++;
            }
        }

        if ($okCnt > 0) {
            echo json_encode(array('status'=>'ok','error_msg'=>'成功生成'.$okCnt.'条记录,失败'.(count($fields)-$okCnt).'条','url'=>'?c=adminErp&a=getProductDetail&pid='.$pid)); exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'成功生成'.$okCnt.'条记录,失败'.(count($fields)-$okCnt).'条')); exit;
    }

    /**
     * 货品详情
     */
    public function dogetProductDetail() {
        $pid = common::request('pid','R',0);//货品ID
        $list = $this->load('adminErp')->getProductDetail($pid);
        $this->view->assign('list',$list);
        $this->view->display('erp/productDetail');
    }

    /**
     * 添加货品列表
     */
    public function doaddErpProductList() {
        //查询分类
        $arrCategoryList = $this->load('adminErp')->getCategoryListForSelect();
        $this->view->assign('arrCategoryList', $arrCategoryList);
        $this->view->display('erp/addErpProductList');
    }

    /**
     * 上传货品图片
     */
    public function doajaxUploadImage() {
        if (!$_FILES || ($_FILES['imgFile']['size'] == 0)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'请选择上传文件!'));
            exit;
        }
        $pid = common::request('pid','R',0);//货品ID
        $attrValueId = common::request('attrValueId','R',0);
        $adminerp_mod = $this->load('adminErp');
        if ($attrValueId) {
            //货品规格图片
            $imageName ='erp_attrval_'.md5(microtime(TRUE).$_FILES['imgFile']['name']);
            $image_url = $this->load('qiniu')->uploadQiNiuImg('imgFile',$imageName);
            $mixResult = $adminerp_mod->updateStandVal([
                'id'=>$attrValueId,
                'img_source'=>$image_url
            ]);
            $adminerp_mod->addErpLog(2,$attrValueId,2,' 规格ID为'.$attrValueId.' 上传图片:'.$image_url);
        }else{
            //默认货品图片
            $imageName ='erp_product_'.md5(microtime(TRUE).$_FILES['imgFile']['name']);
            $image_url = $this->load('qiniu')->uploadQiNiuImg('imgFile',$imageName);
            
            $mixResult = $adminerp_mod->addProductImage($pid, $image_url);
        }
        if($pid){
            if (!$mixResult) {
                echo json_encode(array('status'=>'fail','error_msg'=>'上传失败'));exit;
            }
            $adminerp_mod->addErpLog(2,$pid,2,' 货品ID为'.$pid.' 上传图片:'.$image_url);
        }
        echo json_encode(array('status'=>'ok','error_msg'=>'上传成功','image'=>$image_url));
    }

    /**
     * 删除货品图片
     */
    public function dodelProductImage() {
        $strImagesId = common::request('imagesId','R');//数组图片
        if (!$strImagesId){
            echo json_encode(array('status'=>'fail','error_msg'=>'参数错误'));exit;
        }
        $arrImagesId = explode(',',$strImagesId);
        $r = $this->load('adminErp')->delProductImages($arrImagesId);
        if (!$r) {
            echo json_encode(array('status'=>'fail','error_msg'=>'删除失败'));exit;
        }
        $this->load('adminErp')->addErpLog(3,0,2,'删除图片,ID:'.implode(',',$arrImagesId));
        echo json_encode(array('status'=>'ok','error_msg'=>'删除成功'));exit;
    }

    /**
     * 货品状态变更
     */
    public function dosetProductStatus() {
        $pid = common::request('pid','R','');//货品ID
        $status = common::request('status','R',0);//状态ID
        if (!$pid) {
            echo json_encode(array('status'=>'fail','error_msg'=>'参数丢失'));exit;
        }
        $statusLogMsg = '';
        if ($status == 0) {
            $statusLogMsg ='状态由停售变为开售';
        } else {
            $statusLogMsg ='状态由开售变为停售';
        }
        $status = $status ? 0 : 5;
        $re = $this->load('adminErp')->setProductStatus($pid, $status);
        if (!$re) {
            echo json_encode(array('status'=>'fail','error_msg'=>'更新失败'));exit;
        }
        $this->load('adminErp')->addErpLog(2,$pid,2,'货品ID为'.$pid.'的货品，'.$statusLogMsg);
        echo json_encode(array('status'=>'ok','error_msg'=>'更新成功','url'=>''));
    }

    /**
     * 新增货品操作
     */
    public function doaddErpProduct() {
        $name = common::request('name','R','');//货品名称
        $cid = common::request('cid','R','');//分类ID
        $express_fee = common::request('express_fee','R','');//运费
        $image  = common::request('image','R','');
        if (!$name) {
            echo json_encode(array('status'=>'fail','error_msg'=>'货品名称必填'));exit;
        }
        $name = strtolower($name);//统一转化小写
        $boolIsExist = $this->load('adminErp')->productIsExist(0,$name);
        if ($boolIsExist) {
            echo json_encode(array('status'=>'fail','error_msg'=>'货品名称重复'));exit;
        }
        if (!$cid) {
            echo json_encode(array('status'=>'fail','error_msg'=>'类别必填'));exit;
        }
        $result= $this->load('adminErp')->addErpProduct(array('name'=>$name,'category_id'=>$cid,'image'=>$image,'express_fee'=>$express_fee));
        if ($result) {
            echo json_encode(array('status'=>'ok','error_msg'=>'操作成功','url'=>'index.php?c=adminErp&a=getErpProductList'));exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));
    }
    
    public function doupdateErpProduct(){
        $id = common::request('id','R','');
        $title = trim(common::request('title','R',''));
        if(!$id){
            echo json_encode(array('status'=>'fail','error_msg'=>'缺少id'));
            exit;
        }
        if(!$title){
            echo json_encode(array('status'=>'fail','error_msg'=>'缺少标题'));
            exit;
        }
        $res = $this->load('adminErp')->updateErpProduct(compact('id','title'));
        if($res){
            echo json_encode(array('status'=>'ok','error_msg'=>'操作成功','url'=>'index.php?c=adminErp&a=getErpProductList'));exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));
    }

    public function doupdateErpProductExpress(){
        $id = common::request('id','R','');
        $express_fee = trim(common::request('express','R',''));
        if(!$id){
            echo json_encode(array('status'=>'fail','error_msg'=>'缺少id'));
            exit;
        }

        $res = $this->load('adminErp')->updateErpProduct(compact('id','express_fee'));
        if($res){
            echo json_encode(array('status'=>'ok','error_msg'=>'操作成功','url'=>'index.php?c=adminErp&a=getErpProductList'));exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));
    }


    /**
     * 规格管理
     */
    public function doaddErpProStandard() {
        $pid = common::request('pid','R','');//货品ID
        if (!$pid) {
            common::tips('货品参数丢失');
            exit;
        }
        $adminerp_mod = $this->load('adminErp');
        $productInfo =$adminerp_mod ->getProductInfo($pid,'id,title');
        $this->view->assign('productInfo',$productInfo);
        $this->view->assign('pid',$pid);
        //查询货品的规格
        $info = $adminerp_mod->getProductStandard($pid);

        $info_add = array();
        foreach ($info as $v) {
            $info_add[] = $v['child'];
        }
        if(count($info_add)>1){
            $info_add = $this->load('goods')->getDescartes($info_add);
        }else{
            $arr = array();
            foreach ($info_add as $v){
                foreach ($v as $item) {
                    $arr[][] = $item;
                }
            }
            $info_add = $arr;
        }
        //能不能编辑
        $editable = $adminerp_mod->getGoodsIsExistByPid($pid)? 0 : 1;
        
        $this->view->assign('info',$info);
        $this->view->assign('info_add',$info_add);
        $this->view->assign('editable', $editable);
        $this->view->display('erp/addErpProstandard');
    }

    /**
     * 添加规格名称
     */
    public function doaddStandardHead() {
        $pid = (int)common::request('pid','P',0);
        $name = trim(common::request('name','P',''));
        
        if (!$pid || !$name) {
            echo json_encode(array('status'=>'fail','error_msg'=>'参数丢失'));
            exit;
        }
        $adminerp_mod = $this->load('adminErp');
        //查询规格商品
        $boolIsExist = $adminerp_mod->getGoodsIsExistByPid($pid);
        if ($boolIsExist) {
            echo json_encode(array('status'=>'fail','error_msg'=>'规格商品已生成，货品规格不允许增加'));
            exit;
        }
        $boolIsExist = $adminerp_mod->standardIsExist($pid,$name); //查询规格是否存在
        if ($boolIsExist) {
            echo json_encode(array('status'=>'fail','error_msg'=>'规格名称已存在'));
            exit;
        }
        //写入
        $id = $adminerp_mod->addStandardHead($pid,$name);
        if (!$id) {
            echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));
            exit;
        }
        $adminerp_mod->addErpLog(2,$pid,2,'货品ID为'.$pid.'的货品，增加规格名'.$name.' 规格名ID：'.$id);
        echo json_encode(array('status'=>'ok','error_msg'=>'操作成功','url'=>''));
        exit;
    }
    
    public function doupdateStandardHead(){
        $pid = (int)common::request('pid','P',0);
        $name = trim(common::request('name','P',''));
        $id = common::request('id','P','');
        
        if (!$id || !$name) {
            echo json_encode(array('status'=>'fail','error_msg'=>'参数丢失'));
            exit;
        }
        $adminerp_mod = $this->load('adminErp');
        $boolIsExist = $adminerp_mod->standardIsExist($pid,$name); //查询规格是否存在
        if ($boolIsExist) {
            echo json_encode(array('status'=>'fail','error_msg'=>'规格名称已存在'));
            exit;
        }
        $id = $adminerp_mod->updateStandardHead($id,$name);
        if (!$id) {
            echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));
            exit;
        }
        $adminerp_mod->addErpLog(2,$pid,2,'货品ID为'.$pid.'的货品，修改规格名'.$name.' 规格名ID：'.$id);
        echo json_encode(array('status'=>'ok','error_msg'=>'操作成功','url'=>''));
        exit;
    }
    
    public function dodelStandardHead(){
        $id = common::request('id','R','');
        if(!is_numeric($id)){
            echo json_encode([
                'status'=>'error',
                'error_msg'=>'id错误'
            ]);
            exit;
        }
        
        $count = $this->erpManageDb->getOne('select count(*) from r_goodattr_value where head_id ='.$id);
        
        if($count){
            echo json_encode([
                'status'=>'error',
                'error_msg'=>'还有规格值'
            ]);
            exit;
        }
        
        $res = $this->load('adminErp')->delStandardHead($id);
        if($res){
            echo json_encode(array('status'=>'ok','error_msg'=>'操作成功','url'=>''));
        }
    }

    /**
     * 添加规格值
     */
    public function doaddStandardVal() {
        $headId = common::request('headId','P','');
        $strStandVal = common::request('strStandVal','P','');
        if (!$headId || !$strStandVal) {
            echo json_encode(array('status'=>'fail','error_msg'=>'参数丢失'));
            exit;
        }
        $arrStandVal = array_filter(explode('|',$strStandVal));

        $uniqueArr = array_unique($arrStandVal);//数组是否有重复的值
        if (count($uniqueArr) <> count($arrStandVal)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'输入的规格值不能重复'));
            exit;
        }
        $adminerp_mod = $this->load('adminErp');
        $arrExistStandVal = $adminerp_mod->standardValIsExist($headId,$arrStandVal); //已存在的规格值
        if($arrExistStandVal) {
            $str = '';
            foreach ($arrExistStandVal as $k => $v) {
                $str = $v['title'] . ',';
            }
            echo json_encode(array('status' => 'fail', 'error_msg' => '系统中存在相同的规格值:' . substr($str, 0, -1)));
            exit;
        }
        $standHead = $adminerp_mod->getStandHeadInfo($headId,'product_id');//货品info
        if (!$standHead || !$standHead['product_id'])  {
            echo json_encode(array('status' => 'fail', 'error_msg' => '货品ID丢失'));
            exit;
        }
        //写入
        foreach($arrStandVal as $val){
            $re = $adminerp_mod->addStandVal($headId,$standHead['product_id'],$val);
        }
        if (!$re) {
            echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));
            exit;
        }
        $adminerp_mod->addErpLog(2,$standHead['product_id'],2,'货品ID为'.$standHead['product_id'].'的货品，增加规格值'.implode('|',$arrStandVal));
        echo json_encode(array('status'=>'ok','error_msg'=>'操作成功','url'=>''));
        exit;
    }
    
    public function doupdateStandardVal(){
        $headId = common::request('headId','P','');
        $strStandVal = common::request('strStandVal','P','');
        $id = common::request('id','P','');
        
        if (!$headId) {
            echo json_encode(array('status'=>'fail','error_msg'=>'参数丢失'));
            exit;
        }
        $adminerp_mod = $this->load('adminErp');
        $re = $adminerp_mod->updateStandVal([
            'id'=>$id,
            'title'=>$strStandVal
        ]);
        if (!$re) {
            echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));
            exit;
        }
        $adminerp_mod->addErpLog(2,$headId,2,'规格头ID为'.$headId.'的货品，修改规格值'.$strStandVal);
        echo json_encode(array('status'=>'ok','error_msg'=>'操作成功','url'=>''));
        exit;
    }
    
    public function dodelStandardVal(){
        $id = common::request('id','R','');
        if(!is_numeric($id)){
            echo json_encode([
                'status'=>'error',
                'error_msg'=>'id错误'
            ]);
            exit;
        }
        $res = $this->load('adminErp')->delStandardVal($id);
        if($res){
            echo json_encode(array('status'=>'ok','error_msg'=>'操作成功','url'=>''));
        }
    }

    /**
     * 添加商品
     */
    public function doaddGoods() {
        $pid = common::request('pid','P',0);//货品ID
        $standValId = common::request('standValId','P',0);//规格ID
        $stockIntoCnt = common::request('stockIntoCnt','P',0);//入库数量
        $price = common::request('price','P',0);//单价
        $imageId =  common::request('imageId','P',0);//图片ID
        if (!$pid || !$standValId || !$stockIntoCnt || !$price) {
            echo json_encode(array('status'=>'fail','error_msg'=>'参数丢失')); exit;
        }

        /*******************数据检测START******************/
        //查询规格数量是否匹配
        $existCnt = $this->load('adminErp')->getProductHeadCnt($pid);
        if ($existCnt == 0) {
            echo json_encode(array('status'=>'fail','error_msg'=>'请先添加规格')); exit;
        }
        $cnt = count($standValId);
        if ($cnt==0 || ($cnt%$existCnt <>0)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'规格数目不对，请刷新重试')); exit;
        }
//        $i = 1;
//        foreach ($standValId as $key=>$val) {
//            $c=  'a'.$i;
//            if ($i%$existCnt ==0) {
//                $a{$c}[] = $val;
//                $i=0;
//            } else {
//                $a{$c}[] = $val;
//            }
//            $i++;
//        }
        /**
         * array(1,2,4,6,9) array('1,2','4,6')
         */
//        $a = array(1,2,4,6,9);
        //组合每行分类
        $new = [];
        $tmp = [];
        $i = 0;
        foreach ($standValId as $key=>$val) {
            if ($i==0 ||  ($i%$existCnt <> 0)) {
                $tmp[] = $val;
                if ($i == count($standValId)-1) {  //到达末尾
                    $new[] = implode(',',$tmp);
                    unset($tmp);
                }
            } else {
                $new[] = implode(',',$tmp);
                $tmp = [];
                $tmp[] = $val;
                if ($i == count($standValId)-1) {  //到达末尾
                    $new[] = implode('-',$tmp);
                    unset($tmp);
                }
            }
            $i++;
        }
        if (count(array_unique($new)) <> count($new)) {//每行重复的分类不允许提交
            echo json_encode(array('status'=>'fail','error_msg'=>'请不要添加重复的规格值！')); exit;
        }
        //查询规格商品
        $boolIsExist = $this->load('adminErp')->getGoodsIsExistByPid($pid);
        if ($boolIsExist) {
            foreach ($new as $key=>$val) {
                $boolExistAttr = $this->load('adminErp')->getStrAttrIsExist($pid,$val);
                if ($boolExistAttr) {
                    echo json_encode(array('status'=>'fail','error_msg'=>'请不要添加重复的规格值！！')); exit;
                }
            }
        }

        $fields = [];
        foreach ($stockIntoCnt as $key=>$val) {
            if (count($stockIntoCnt) <> count($new)) {
                echo json_encode(array('status'=>'fail','error_msg'=>'请填写完整入库数量')); exit;
            }
            if (count($price) <> count($new)) {
                echo json_encode(array('status'=>'fail','error_msg'=>'请填写完整单价')); exit;
            }
            if (!preg_match('/^[1-9]+[0-9]*$/',$val,$match)) {
                echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行入库数量是正整数且必须>0')); exit;
            }
            if (!preg_match('/^[1-9][0-9]*(\.[0-9]{1,2})?$/', $price[$key],$match) && !preg_match('/^[0-9]\.0[1-9]$/', $price[$key],$match2) && !preg_match('/^[0-9]\.[1-9][0-9]?$/', $price[$key],$match3)) {
                echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行单价必须>0,最多2位小数')); exit;
            }
            $fields[] = array('attr_path'=>$new[$key],'stockIntoCnt'=>(int)$val,'price'=>(float)round($price[$key],2),'product_id'=>$pid);
        }

        //查询货品值是否匹配
        $arrStandValId = $this->load('adminErp')->getProductVal($pid,'id');
        if (!$arrStandValId) {
            echo json_encode(array('status'=>'fail','error_msg'=>'请先添加规格值')); exit;
        }
        $arrVid = [];
        foreach ($arrStandValId as $key=>$val) {
            $arrVid[] = $val['id'];
        }
        if (array_diff($standValId,$arrVid)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'请选择正确的规格值或刷新重试')); exit;
        }

        /*******************数据检测END******************/
        $okCnt = 0;
        foreach($fields as $key => $val) {
           $r =  $this->load('adminErp')->addGoods($val);
            if ($r) {
                $this->load('adminErp')->addErpLog(2,$val['product_id'],2,'货品ID为'.$val['product_id'].'的货品，增加规格商品，ID：'.$r.',入库数量'.$val['stockIntoCnt'].'件，入库单价:'.$val['price']);
                $okCnt++;
            }
        }

        if ($okCnt == count($fields)) {
            echo json_encode(array('status'=>'ok','error_msg'=>'成功生成'.$okCnt.'条记录','url'=>'?c=adminErp&a=getErpProductList')); exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'成功生成'.$okCnt.'条记录,失败'.(count($fields)-$okCnt).'条')); exit;
    }

    /**
     * erp 类别列表
     */
    public function dogetErpProCategory() {
        $name = common::request('name','P','');//名称
        $limit = 20;
        $p = common::request('p', 'G', 1);
        $start = ($p - 1) * $limit;
        $parameter = '';
        if (trim($name)) {
            $params['name'] = $name;
            $parameter .= '&title='."$name";
        }
        $params['start'] = $start;
        $params['limit'] = $limit;
        $info = $this->load('adminErp')->getCategoryList($params);
        if ($info) {
            $arrCid = [];
            foreach($info as $key=>$val) {
                $arrCid[] = $val['id'];
            }
            $cateProCnt = $this->load('adminErp')->getProductCntByCid($arrCid); //分类的商品数量
            foreach($info as $key=>$val) {
                $info[$key]['product_cnt'] = (int)$cateProCnt[$val['id']];
            }
        }
        $total = $this->load('adminErp')->total;
        $this->view->assign('info', $info);
        require FILE . 'lib/page.class.php';
        $page = new Page($total, $limit, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('name', $name);
        $this->view->display('erp/categoryList');
    }

    /**
     * erp货品类别添加
     */
    public function doaddErpProCategory() {
        $id =  (int)common::request('id','P',0);//分类ID
        $name = trim(common::request('remark','P',''));//名称
        if (!$name) {
            echo json_encode(array('status'=>'fail','error_msg'=>'分类名称不能为空')); exit;
        }
        $boolIsExist = $this->load('adminErp')->categoryIsExist($id,$name);
        if ($boolIsExist) {
            echo json_encode(array('status'=>'fail','error_msg'=>'分类名称已存在!'));exit;
        }
        $info = $this->load('adminErp')->getCategoryInfo($id,'title');
        $oldTitle = $info && isset($info['title']) ? $info['title'] : '';
        $res = $this->load('adminErp')->addCategory($id,$name);
        if (!$res) {
            echo json_encode(array('status'=>'fail','error_msg'=>'操作失败!'));exit;
        }
        if (!$id) {
            $this->load('adminErp')->addErpLog(1,$res,4,' 增加了一条分类分类ID为'.$res.' 名称是'.$name);
        } else {
            $this->load('adminErp')->addErpLog(2,$id,4,' 分类ID为'.$id.' 名称由'.$oldTitle.' 修改为'.$name);
        }
        echo json_encode(array('status'=>'ok','error_msg'=>'操作成功!','url'=>'?c=adminErp&a=getErpProCategory'));
    }

    /**
     * erp 物流模板列表
     */
    public function dogetLogisticsTep() {
        $name = common::request('name','P','');//名称
        $limit = 20;
        $p = common::request('p', 'G', 1);
        $start = ($p - 1) * $limit;
        $parameter = '';
        if (trim($name)) {
            $params['name'] = $name;
            $parameter .= '&title='."$name";
        }
        $params['start'] = $start;
        $params['limit'] = $limit;
        $info = $this->load('adminErp')->getLogisticsTepList($params);
        $total = $this->load('adminErp')->total;
        $this->view->assign('info', $info);
        require FILE . 'lib/page.class.php';
        $page = new Page($total, $limit, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('name', $name);
        $this->view->display('erp/logisticsTepList');
    }

    /**
     * erp 编辑物流
     */
    public function doaddLogisticsTep() {
        $id =  (int)common::request('id','P',0);//模板ID
        $name = trim(common::request('remark','P',''));//名称
        if (!$name) {
            echo json_encode(array('status'=>'fail','error_msg'=>'模板名称不能为空')); exit;
        }
        $boolIsExist = $this->load('adminErp')->logisticsTepIsExist($id,$name);
        if ($boolIsExist) {
            echo json_encode(array('status'=>'fail','error_msg'=>'模板名称已存在!'));exit;
        }
        $info = $this->load('adminErp')->getlogisticsTepInfo($id,'title');
        $oldTitle = $info && isset($info['title']) ? $info['title'] : '';

        $res = $this->load('adminErp')->addLogisticsTep($id,$name);
        if (!$res) {
            echo json_encode(array('status'=>'fail','error_msg'=>'操作失败!'));exit;
        }
        if (!$id) {
            $this->load('adminErp')->addErpLog(1,$res,3,' 新增了一条物流模板ID为'.$res.' 名称是'.$name);
        } else {
            $this->load('adminErp')->addErpLog(2,$id,3,'物流模板ID为'.$id.' 名称由'.$oldTitle.' 修改为'.$name);
        }
        echo json_encode(array('status'=>'ok','error_msg'=>'操作成功!','url'=>'?c=adminErp&a=getLogisticsTep'));
    }

    /**
     * erp 盘点列表
     */
    public function dogetStockCheck() {
        $pid = common::request('pid','R',0);
        $productInfo = $this->load('adminErp')->getProductInfo($pid,'id,code,title');//货品信息
        if (!$productInfo) {
            common::tips('未查询到货品');
            exit;
        }
        $list = $this->load('adminErp')->getGoodsByPid($pid);//查询规格商品
        $this->view->assign('productInfo',$productInfo);
        $this->view->assign('list',$list);
        $this->view->display('erp/stockCheckList');
    }

    /**
     * erp 盘点操作
     */
    public function doaddStockCheck() {
        $gid = common::request('gid','P',0);
        $realStockNum = common::request('stockNum','P',0);
        $content = common::request('remark','P','');
        $fields = [];
        if (!$gid) {
            echo json_encode(array('status'=>'fail','error_msg'=>'请先勾选'));exit;
        }
        foreach($gid as $key=>$val) {
            if(!is_numeric($val)){
                echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行规格商品ID丢失'));exit;
            }
            if (!isset($realStockNum[$key]) || !preg_match('/^[1-9]+[0-9]*$/',$realStockNum[$key],$match)) {
                echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行实际库存必须是整数'));exit;
            }
            if (!isset($content[$key]) || !trim($content[$key])) {
                echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行盘点原因必填'));exit;
            }
            $fields[] = array('gid'=>$val,'num'=>$realStockNum[$key],'content'=>$content[$key]);
        }
        $i = 0;
        $pid = 0;
        foreach($fields as $key=>$val) {
            //查询规格商品信息
            $info = $this->load('adminErp')->getGoodsInfo($val['gid'],'product_id,stock_into_num,sale_num,real_stock_num');
            if (!$info) {
                return false;
            }
            $pid = $info['product_id'];
            $re = $this->load('adminErp')->checkStock($info['product_id'],$info['real_stock_num'],$val['gid'],$val['num'],$val['content']);
            if ($re) {
                $this->load('adminErp')->addErpLog(2,$info['product_id'],2,' 货品ID为'.$info['product_id'].'规格商品ID为'.$val['gid'].',盘点库存，当前库存数量'.$info['real_stock_num'].'件，实际库存数量：'.$val['num'].'件，盘点原因：'.$val['content']);
                $i++;
            }
        }
        echo json_encode(array('status'=>'ok','error_msg'=>'成功盘点'.$i.'条,失败'.bcsub(count($fields),$i).'条','url'=>'?c=adminErp&a=getProductDetail&pid='.$pid));
    }

    /**
     * 订单excel 导出
     */
    public function dogetErpOrderExportExcel() {
        //查询待发货订单
        $list = $this->load('order')->getOrderListForWaitSend();
        include_once FILE . 'lib/phpexcel/Classes/PHPExcel.php';
        $fileName = 'erpAdminOrderExport-'.date('Y-m-d H:i:s');
        $cacheMethod =PHPExcel_CachedObjectStorageFactory::cache_to_sqlite3;
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
        $PHPExcel = new PHPExcel();
        //设置列宽
        $PHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
        $PHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(5);
        $PHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(60);
        $PHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(60);
        $PHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
        $PHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(5);
        $PHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(5);
        $PHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(5);
        $PHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
        $PHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
        $PHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(100);
        //填入表头
        $PHPExcel->getActiveSheet()->setCellValue('A1', '订单编号');
        $PHPExcel->getActiveSheet()->setCellValue('B1', '收件人');
        $PHPExcel->getActiveSheet()->setCellValue('C1', '固话');
        $PHPExcel->getActiveSheet()->setCellValue('D1', '手机');
        $PHPExcel->getActiveSheet()->setCellValue('E1', '地址');
        $PHPExcel->getActiveSheet()->setCellValue('F1', '发货信息');
        $PHPExcel->getActiveSheet()->setCellValue('G1', '备注');
        $PHPExcel->getActiveSheet()->setCellValue('H1', '待收金额');
        $PHPExcel->getActiveSheet()->setCellValue('I1', '保价金额');
        $PHPExcel->getActiveSheet()->setCellValue('J1', '业务类型');
        $PHPExcel->getActiveSheet()->setCellValue('K1', '订单类型');
        $PHPExcel->getActiveSheet()->setCellValue('L1', '活动ID');
        $PHPExcel->getActiveSheet()->setCellValue('M1', '商品（标题，属性，数量，单价，总价）');
        $PHPExcel->getActiveSheet()->setCellValue('N1', '是否达标');
        //填入列表
        $ks = 0;
        $actType = common::$actType;
        foreach ($list as $k => $v){
            $PHPExcel->getActiveSheet()->setCellValueExplicit('A'.($k+2), $v['ordersn'],PHPExcel_Cell_DataType::TYPE_STRING);
            $PHPExcel->getActiveSheet()->setCellValue('B'.($k+2), $v['name']);
            $PHPExcel->getActiveSheet()->setCellValue('C'.($k+2), '');
            $PHPExcel->getActiveSheet()->setCellValueExplicit('D'.($k+2), $v['phone'],PHPExcel_Cell_DataType::TYPE_STRING);
            $PHPExcel->getActiveSheet()->setCellValue('E'.($k+2), $v['address']);
            $PHPExcel->getActiveSheet()->setCellValue('F'.($k+2), $v['strGoodsList']);
            $PHPExcel->getActiveSheet()->setCellValue('G'.($k+2), $v['mark']);
            $PHPExcel->getActiveSheet()->setCellValue('H'.($k+2),"");
            $PHPExcel->getActiveSheet()->setCellValue('I'.($k+2),"");
            $PHPExcel->getActiveSheet()->setCellValue('J'.($k+2),"");
            $PHPExcel->getActiveSheet()->setCellValue('K'.($k+2), $actType[$v['act_type']]);
            $PHPExcel->getActiveSheet()->setCellValue('L'.($k+2), $v['act_id']);
            $PHPExcel->getActiveSheet()->getStyle('M'.($k+2))->getAlignment()->setWrapText(true);
            $PHPExcel->getActiveSheet()->setCellValue('N'.($k+2), $v['strGoodsList']);
            $dabiao = 0;
            if($v['act_type']==1 && $v['act_id']){
                $dabiao = $this->db->getOne("select dabiao from r_match_add where `type`='user' and uid={$v['uid']} and match_id={$v['act_id']} limit 1");
            }
            $PHPExcel->getActiveSheet()->setCellValue('N'.($k+2), $dabiao ? '是' : '');
            $ks++;
        }
        //保存为2003格式
        $objWriter = new PHPExcel_Writer_Excel5($PHPExcel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");

        //多浏览器下兼容中文标题
        $encoded_filename = urlencode($fileName);
        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '.xls"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '.xls"');
        } else {
            header('Content-Disposition: attachment; filename="' . $fileName . '.xls"');
        }

        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }

    /**
     * 导入
     */
    public function dogetErpOrderImportExcel () {
        ini_set('memory_limit','1024M');
        $num = strrpos($_FILES['excelFile']['name'],'.');
        if ($num === false) {
            common::tips('文件名有误');
            exit;
        }
        $excelName = substr($_FILES['excelFile']['name'],0,$num).'-'.date('Y-m-d H:i:s').'-'.uniqid();
        $excelUrl = $this->load('qiniu')->uploadQiNiuExcel('excelFile', $excelName);
        if (!$excelUrl) {
            common::tips('上传失败');
            exit;
        }

        include_once FILE . 'lib/phpexcel/Classes/PHPExcel.php';
        $objPHPExcel = PHPExcel_IOFactory::load($_FILES['excelFile']['tmp_name']);
        $arrExcel = $objPHPExcel->getSheet(0)->toArray();
        array_shift($arrExcel); array_shift($arrExcel);
        $totalCnt = count($arrExcel);
        if (!$totalCnt) {
            common::tips('上传内容为空');
            exit;
        }

        //查询订单编号是否为空
        foreach ($arrExcel as $key => $val ) {
            if (!$val[1]) {
                common::tips('第'.($key+2).'行订单编号不能为空');
                exit;
            }
        }

        $importId = $this->load('adminErp')->addOrderImport(array(
            'totalNum'=>$totalCnt,
            'successNum'=>0,
            'excelUrl'=>$excelUrl
        ));//写入总记录表

        if (!$importId) {
            common::tips('总记录信息记录失败');
            exit;
        }

        $goods_mod = $this->load('goods');
        $successNum = 0;
        foreach ($arrExcel as $key => $val ) {
            $orderId = $val[1];//订单编号
            $sql = "select
                        id,
                        status,
                        pay_status,
                        order_id,
                        `name`,
                        phone,
                        province,
                        city,
                        district,
                        address,
                        goods,
                        mark
                        from r_order where order_id ='$orderId'";
            $info = $this->erpDb->getRow($sql);
            if (!$info) {
                $this->load('adminErp')->addOrderImportDetail(array(
                    'importId'=>$importId,
                    'orderId'=>$orderId,
                    'status'=>-5,
                    'reason'=>'未查询到订单'
                ));
                continue;
            }
            if ($info['status'] <> 1 || $info['pay_status'] <>20) {
                    $this->load('adminErp')->addOrderImportDetail(array(
                        'importId'=>$importId,
                        'orderId'=>$orderId,
                        'status'=>-5,
                        'reason'=>'订单状态错误'
                    )
                );
                continue;
            }
           if ($info['name'] != $val[2]) {
               $this->load('adminErp')->addOrderImportDetail(array(
                       'importId'=>$importId,
                       'orderId'=>$orderId,
                       'status'=>-5,
                       'reason'=>'收件人错误'
                   )
               );
               continue;
           }
            if ($info['phone'] != $val[3]) {
                $this->load('adminErp')->addOrderImportDetail(array(
                        'importId'=>$importId,
                        'orderId'=>$orderId,
                        'status'=>-5,
                        'reason'=>'电话错误'
                    )
                );
                continue;
            }
            $address = $info['province'].' '.$info['city'].' '.$info['district'].'  '.$info['address'];

            if (trim($address) != trim($val[4])) {
                $this->load('adminErp')->addOrderImportDetail(array(
                        'importId'=>$importId,
                        'orderId'=>$orderId,
                        'status'=>-5,
                        'reason'=>'地址错误'
                    )
                );
                continue;
            }

            //物流
            if(!$val[14]) {
                $this->load('adminErp')->addOrderImportDetail(array(
                        'importId'=>$importId,
                        'orderId'=>$orderId,
                        'status'=>-5,
                        'reason'=>'快递单号错误'
                    )
                );
                continue;
            }

            $arrLogistics = $this->load('adminErp')->getlogisticsTepInfoByName($val[13],'id');//物流名称
            if (!$arrLogistics['id']) {
                $this->load('adminErp')->addOrderImportDetail(array(
                        'importId'=>$importId,
                        'orderId'=>$orderId,
                        'status'=>-5,
                        'reason'=>'快递名称错误'
                    )
                );
                continue;
            }

            $goodsList = [];
            $goodsMergeInfo = [];
            if (!$info['goods'] || !$goods = json_decode($info['goods'],true)) {
                $this->load('adminErp')->addOrderImportDetail(array(
                        'importId'=>$importId,
                        'orderId'=>$orderId,
                        'status'=>-5,
                        'reason'=>'系统订单商品信息不存在!'
                    )
                );
                continue;
            }
            foreach($goods as $goodsInfo) {
                $_goods = $goods_mod->getRaceGoodsInfo($goodsInfo['id']);
                if(!$_goods){
                    $this->load('adminErp')->addOrderImportDetail(array(
                            'importId'=>$importId,
                            'orderId'=>$orderId,
                            'status'=>-5,
                            'reason'=>'系统订单商品信息不存在!!'
                        )
                    );
                    continue 2;
                }

                if (!isset($goodsInfo['num']) || !isset($_goods['goodsInfo']['erpRealStockNum'])) {//系统错误
                    $this->load('adminErp')->addOrderImportDetail(array(
                            'importId'=>$importId,
                            'orderId'=>$orderId,
                            'status'=>-5,
                            'reason'=>'系统订单商品数量参数丢失'
                        )
                    );
                    continue 2;
                }
                if ($_goods['goodsInfo']['erpRealStockNum'] < $goodsInfo['num']) {//查询库存数量
                    $this->load('adminErp')->addOrderImportDetail(array(
                            'importId'=>$importId,
                            'orderId'=>$orderId,
                            'status'=>-5,
                            'reason'=>'库存不足'
                        )
                    );
                    continue 2;
                }
                $productName = isset($_goods['product']['title']) ? $_goods['product']['title'] : '';
                $strAttrPathName = isset($_goods['goodsInfo']['attrPathName']) ? $_goods['goodsInfo']['attrPathName'] : '';
                $goodsMergeInfo[] = $productName.' '.$strAttrPathName;
                $goodsList[] = array('gid'=>$_goods['goodsInfo']['erpGoodId'],'num'=>$goodsInfo['num']);
            }
            /*
            $strGoodsMergeInfo = implode(',',$goodsMergeInfo);
            if ($strGoodsMergeInfo != $val[5]) {
                $this->load('adminErp')->addOrderImportDetail(array(
                        'importId'=>$importId,
                        'orderId'=>$orderId,
                        'status'=>-5,
                        'reason'=>'发货信息错误'
                    )
                );
                continue;
            }*/

            $detailId = $this->load('adminErp')->addOrderImportDetail(array(
                'importId'=>$importId,
                'orderId'=>$orderId,
                'reason'=>'',
                'status'=>0
            ));
            if ($detailId) {
                $successNum++;
                //更新订单为已发货
                $sendTime =time();
                //$re = $this->erpDb->update("update r_order set status=2,logistic_code='{$val[14]}',logistic_id={$arrLogistics['id']},send_goods_time=$sendTime where order_id=$orderId and status=1 and pay_status=20");
                $re = $this->erpDb->update("update r_order set status=2,shipping_id={$arrLogistics['id']} where order_id=$orderId and status=1 and pay_status=20");
                //记录全局日志
                if (!$re) {
                    $this->load('adminErp')->addErpLog(2,$info['id'],1,'更新失败，订单编号:'.$orderId.' 执行操作：后台订单状态由待发货变为已发货');
                } else {
                    $this->load('adminErp')->addErpLog(2,$info['id'],1,'更新成功，后台订单状态由待发货变为已发货，订单编号:'.$orderId);
                    $r2 = $this->load('order')->addOrderAction(array('id'=>3,'order_id'=>$orderId,'shipping_id'=>$arrLogistics['id'],'shipping_status'=>1,'shipping_num'=>$val[14],'uid'=>$this->realUser['uid']));
                    //货品库存数量减少
                    foreach ($goodsList as $kg=>$vg) {
                        $this->load('adminErp')->saleGoods($vg['gid'],$vg['num']);
                    }
                }

            }
        }
        if ($successNum > 0) {//更新总记录成功条数
            $this->load('adminErp')->saveOrderImport(array(
                'id'=>$importId,
                'successNum'=>$successNum
            ));
        }
        common::tips('导入完成','/index.php?c=admin&a=orderList');
    }

    /*
   * 商品搜索
   */
    public function doSearchProduct(){
        $keywords = trim(common::request('keywords','G'));
        $sql = "select code as id,title as name  from r_product where status=5 and title like '%$keywords%' order by create_time desc limit 10";
        $data = $this->erpManageDb->getAll($sql);
        echo  json_encode($data);
    }
}